package com.gitee.linmt.service.impl;

import com.gitee.linmt.entity.Permission;
import com.gitee.linmt.entity.Role;
import com.gitee.linmt.entity.UserRole;
import com.gitee.linmt.repository.RoleRepository;
import com.gitee.linmt.service.PermissionService;
import com.gitee.linmt.service.RoleService;
import com.gitee.linmt.service.UserRoleService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author linmt
 */
@Service
public class RoleServiceImpl implements RoleService {

    private final RoleRepository roleRepository;
    private final UserRoleService userRoleService;
    private final PermissionService permissionService;

    public RoleServiceImpl(RoleRepository roleRepository, UserRoleService userRoleService, PermissionService permissionService) {
        this.roleRepository = roleRepository;
        this.userRoleService = userRoleService;
        this.permissionService = permissionService;
    }

    @Override
    public List<Role> listByUserId(Integer userId) {
        List<UserRole> userRoles = userRoleService.listByUserId(userId);
        if (CollectionUtils.isEmpty(userRoles)) {
            return new ArrayList<>();
        }
        Set<Integer> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
        List<Role> roles = roleRepository.findAllById(roleIds);
        Map<Integer, List<Permission>> roleIdToPermissions = permissionService.listByRoleIds(roleIds);
        for (Role role : roles) {
            role.setPermissions(roleIdToPermissions.getOrDefault(role.getId(), new ArrayList<>()));
        }
        return roles;
    }
}
